package main

import (
	"errors"
	"sync"
	"sync/atomic"
	"time"
)

var messInitState atomic.Bool

func main() {

}

func init() {

}

func MessInitReg01() error {
	if time.Now().UnixNano()%2 == 0 {
		return nil
	} else {
		return errors.New("Error! ")
	}
}

func MessInitReg02() bool {
	return time.Now().UnixNano()%2 == 0
}

func MessInitReg99() error {
	if messInitState.Load() {
		return nil
	}
	if time.Now().UnixNano()%2 == 0 {
		messInitState.Store(true)
		return nil
	} else {
		return errors.New("Error! ")
	}
}

func Do20400() {
	const (
		minInterval   = 2 * time.Second
		maxInterval   = 24 * time.Hour
		resetInterval = 10 * time.Second
	)
	var newInterval time.Duration
	var err error
	newInterval = resetInterval
	err = MessInitReg01()
	if err == nil {
		newInterval = newInterval * 2
		if newInterval > maxInterval {
			newInterval = resetInterval
		}
	} else {
		newInterval = newInterval / 2
		if newInterval < minInterval {
			newInterval = minInterval
		}
	}
}
func Do20401() {
	const (
		initialInterval = 10 * time.Second
		minInterval     = 2 * time.Second
		maxInterval     = 24 * time.Hour
		resetInterval   = 10 * time.Second
		backoffFactor   = 0.5
		successFactor   = 2.0
	)
	var currentInterval time.Duration = initialInterval

	registered := MessInitReg02()

	if registered {
		// 注册成功，延长检查间隔
		newInterval := time.Duration(float64(currentInterval) * successFactor)
		if newInterval > maxInterval {
			// 超过一天则重置为初始间隔
			currentInterval = resetInterval
		} else {
			currentInterval = newInterval
		}
	} else {
		// 注册失败，缩短检查间隔
		newInterval := time.Duration(float64(currentInterval) * backoffFactor)
		if newInterval < minInterval {
			// 不低于最小间隔
			currentInterval = minInterval
		} else {
			currentInterval = newInterval
		}
	}
}

func Do20402() {
	var (
		defaultCheckInterval = 10 * time.Second
		minCheckInterval     = 2 * time.Second
		maxCheckInterval     = 24 * time.Hour
	)

	// 初始检查周期
	checkInterval := defaultCheckInterval
	// 用来追踪当前是否注册成功
	isRegistered := MessInitReg02()

	if !isRegistered {
		// 如果没有注册成功，检查消息注册函数
		success := MessInitReg02()
		if success {
			// 注册成功，延长检查周期
			checkInterval *= 2
			if checkInterval > maxCheckInterval {
				checkInterval = maxCheckInterval
			}
			isRegistered = true
		} else {
			// 注册失败，缩短检查周期，确保不小于2秒
			checkInterval /= 2
			if checkInterval < minCheckInterval {
				checkInterval = minCheckInterval
			}
		}
	} else {
		checkInterval *= 2
		if checkInterval > maxCheckInterval {
			checkInterval = maxCheckInterval
		}
	}
}

func Do20403() {
	const (
		minInterval   = 2 * time.Second
		maxInterval   = 24 * time.Hour
		startInterval = 10 * time.Second
	)

	interval := startInterval
	successCount := 0

	success := MessInitReg02()

	if success {
		successCount++
		if interval < maxInterval {
			interval *= 2
			if interval > maxInterval {
				interval = startInterval
			}
		} else {
			interval = startInterval
		}
	} else {
		successCount = 0
		// 重试注册
		successRetry := MessInitReg02()
		if successRetry {
			interval *= 2
			if interval > maxInterval {
				interval = startInterval
			}
		} else {
			interval /= 2
			if interval < minInterval {
				interval = minInterval
			}
		}
	}
}

func Do20404() {
	// 定义检查周期的范围
	const (
		initialInterval = 10 * time.Second
		minInterval     = 2 * time.Second
		maxInterval     = 24 * time.Hour
	)

	// 初始化检查周期
	currentInterval := initialInterval

	registered := MessInitReg02()
	if registered {
		currentInterval *= 2
		if currentInterval > maxInterval {
			currentInterval = initialInterval
		}
	} else {
		// 注册失败，缩短下次检查周期
		currentInterval /= 2
		// 如果小于最小周期，重置为初始周期
		if currentInterval < minInterval {
			currentInterval = initialInterval
		}
	}
}

func Do20405() {
	testC := &MessageRegistrationChecker{
		initialInterval:       10 * time.Second,
		minInterval:           2 * time.Second,
		maxInterval:           24 * time.Hour,
		currentInterval:       10 * time.Second,
		stopCh:                make(chan struct{}),
		checkRegistrationFunc: MessInitReg02,
		registrationFunc:      MessInitReg02,
	}
	defer func() {
		testC.mutex.Lock()
		testC.isRunning = false
		testC.mutex.Unlock()
	}()

	testC.performCheck()
}

func Do20499() {
	var err error
	var chkInterval int64
	const (
		maxChkInterval = 86400
		defMinDuration = 64
		minChkInterval = 2
	)

	err = MessInitReg99()
	if err == nil {
		chkInterval = chkInterval + chkInterval
		if chkInterval > maxChkInterval {
			chkInterval = minChkInterval
		}
	} else {
		chkInterval = chkInterval / 2
		if chkInterval < defMinDuration {
			chkInterval = defMinDuration
		}
	}
}

type MessageRegistrationChecker struct {
	// 配置参数
	initialInterval time.Duration // 初始检查间隔：10秒
	minInterval     time.Duration // 最小检查间隔：2秒
	maxInterval     time.Duration // 最大检查间隔：1天

	// 当前状态
	currentInterval time.Duration // 当前检查间隔
	isRunning       bool          // 是否正在运行
	stopCh          chan struct{} // 停止信号
	mutex           sync.RWMutex  // 读写锁

	// 回调函数
	checkRegistrationFunc func() bool // 检查注册状态的函数
	registrationFunc      func() bool // 消息注册函数 MessInitReg01
}

// performCheck 执行一次检查
func (c *MessageRegistrationChecker) performCheck() {

	// 检查是否已注册
	if c.checkRegistrationFunc() {
		c.handleRegistrationSuccess()
		return
	}

	// 调用消息注册函数
	if c.registrationFunc() {
		c.handleRegistrationSuccess()
	} else {
		c.handleRegistrationFailure()
	}
}

// handleRegistrationSuccess 处理注册成功的情况
func (c *MessageRegistrationChecker) handleRegistrationSuccess() {
	c.mutex.Lock()
	defer c.mutex.Unlock()

	// 延长检查时间（乘以2）
	newInterval := c.currentInterval * 2

	// 如果超过最大间隔（一天），恢复到初始间隔（10秒）
	if newInterval > c.maxInterval {
		c.currentInterval = c.initialInterval
	} else {
		c.currentInterval = newInterval
	}
}

// handleRegistrationFailure 处理注册失败的情况
func (c *MessageRegistrationChecker) handleRegistrationFailure() {
	c.mutex.Lock()
	defer c.mutex.Unlock()

	// 缩短检查时间（除以2）
	newInterval := c.currentInterval / 2

	// 如果小于最小间隔（2秒），恢复到初始间隔（10秒）
	if newInterval < c.minInterval {
		c.currentInterval = c.initialInterval
	} else {
		c.currentInterval = newInterval
	}
}
